<template>
  <div class="page-control-panel">
    <div class="top-gird">
      <div class="welcome">
        <img src="@/assets/images/logo.png" alt="">
        <div class="text">
          <p>{{ userInfo.nickname }}，您好</p>
          <p>欢迎回来！</p>
        </div>
      </div>
      <div class="panel-card">
        <div class="panel-card-item">
          <img src="@/assets/images/wz.png" alt="">
          <span>文章数量</span>
          <AnimateNumber
            @click="navatatorLink('/content-manage/article-manage')"
            :count="countall?.article_count" />
        </div>
        <div class="panel-card-item">
          <img src="@/assets/images/yq.png" alt="">
          <span>友圈数量</span>
          <AnimateNumber
            @click="navatatorLink('/content-manage/share-circle-manage')"
            :count="countall?.circle_count" />
          </div>
          <div class="panel-card-item">
            <img src="@/assets/images/yh.png" alt="">
            <span>用户数量</span>
            <AnimateNumber
              @click="navatatorLink('/user-manage')"
              :count="countall?.user_count" />
          </div>
        <div class="panel-card-item">
          <img src="@/assets/images/bq.png" alt="">
          <span>标签数量</span>
          <AnimateNumber :count="countall?.tag_count" />
        </div>
      </div>
    </div>
    <div class="bottom-gird">
      <div class="modal">
        <div class="block">
          <div class="title" >
            <i style="color: #0dd5e9" class="ri-bar-chart-box-fill"></i>
            <p>近12个月文章/友圈发布数量趋势</p>
          </div>
          <div class="c" id="publishTrend"></div>
        </div>
        <div class="block">
          <div class="title">
            <i style="color: #20d7d1" class="ri-earth-fill"></i>
            <p>站点访问位置分布</p>
          </div>
          <div class="c" style="padding: 6px;">
            <Map :dataList="cityVisitCounts"></Map>
          </div>
        </div>
        <div class="block">
          <div class="title">
            <i style="color: #ef451b" class="ri-bookmark-2-fill"></i>
            <p>标签库</p>
          </div>
          <div class="c" id="hotTag"></div>
        </div>
      </div>
      <div class="modal col-2">
        <div class="block">
          <div class="title">
            <i style="color: #c11616" class="ri-firefox-fill"></i>
            <p>文章热度排行榜</p>
          </div>
          <div class="c" id="hotArticle">
            <el-table stripe :data="rankArticleList" style="height: 100%">
              <el-table-column prop="rankId" label="排名" width="60">
                <template #default="{ row }">
                  <span class="rank-span">{{ row.rankId }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="articleTitle" label="文章" showOverflowTooltip />
              <el-table-column prop="nickname" label="作者" showOverflowTooltip align="center" />
              <el-table-column prop="createTime" label="发布时间" width="180" align="center" />
              <el-table-column prop="viewCounts" label="浏览次数" align="center" />
            </el-table>
          </div>
        </div>
        <div class="block">
          <div class="title">
            <i style="color: #a412f4" class="ri-markdown-fill"></i>
            <p>近30天天站点日访问量</p>
          </div>
          <div class="c" id="visitCount"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="Index">
import { useRouter } from 'vue-router'
import { init, type EChartsType } from 'echarts'
import { ref, shallowRef, onMounted, onBeforeUnmount } from 'vue'
import { dealBasicChartOptions } from './charts'
import AnimateNumber from '@/components/AnimateNumber.vue'
import { storeToRefs } from 'pinia'
import { useUsersStore } from '@/stores'
import Map from '@/components/Map.vue'
import 'echarts-wordcloud'
import {
  apiGetPublicTrend,
  apiGetVisitCounts,
  apiGetHotTags,
  apiGetCountall,
  apiGetHotArticles,
  apiGeCityVisitCount
} from '@/http/service'

interface Countall {
  'article_count': number
  'user_count': number
  'circle_count': number
  'tag_count': number
}
interface PublicTrend{
  month: string
  'article_count': number
  'circle_count': number
}

interface VisitCount {
  'visit_date': string
  'visit_count': number
}
interface Article {
  rankId: number
  articleTitle: string
  createTime: string
  viewCounts: number
  nickname: string
}
const { userInfo } = storeToRefs(useUsersStore())
const router = useRouter()
const countall = ref<Countall>()
const publishTrendRef = shallowRef<null | EChartsType>(null)
const visitCountRef = shallowRef<null | EChartsType>(null)
const hotTagRef = shallowRef<null | EChartsType>(null)
const rankArticleList = ref<Array<Article>>([])
const cityVisitCounts = ref<Array<any>>([])
onMounted(() => {
  publishTrendRef.value = init(document.getElementById('publishTrend'))
  visitCountRef.value = init(document.getElementById('visitCount'))
  hotTagRef.value = init(document.getElementById('hotTag'))
  window.addEventListener('resize', chartEventResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', chartEventResize)
  publishTrendRef.value && publishTrendRef.value.dispose()
  visitCountRef.value && visitCountRef.value.dispose()
  hotTagRef.value && hotTagRef.value.dispose()
})

async function statisticCountall () {
  const data = await apiGetCountall<Countall>()
  countall.value = data
}

async function getPublicTrend () {
  const data = await apiGetPublicTrend<PublicTrend[]>()
  const legend = ['文章', '友圈']
  const xAxis = data.map(o => o.month)
  const options = {
    ...dealBasicChartOptions(legend, xAxis),
    series: [
      {
        name: '文章',
        type: 'line',
        data: data.map(o => o.article_count),
        smooth: true,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#20cc94' },
              { offset: 1, color: '#20cc9400' }
            ]
          }
        },
        symbolSize: 2
      },
      {
        name: '友圈',
        type: 'line',
        data: data.map(o => o.circle_count),
        smooth: true,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#cc20ba' },
              { offset: 1, color: '#cc20ba00' }
            ]
          }
        },
        symbolSize: 2
      }
    ]
  }
  publishTrendRef.value && publishTrendRef.value.setOption(options)
}

async function getVisitCounts () {
  const data = await apiGetVisitCounts<VisitCount[]>()
  const legend = ['日访问量']
  const xAxis = data.map(o => o.visit_date)
  const options = {
    ...dealBasicChartOptions(legend, xAxis),
    tooltip: {
      show: false
    },
    series: [
      {
        name: '日访问量',
        type: 'bar',
        data: data.map(o => o.visit_count),
        label: {
          show: true,
          position: 'top',
          fontSize: 8,
          color: '#20cc94'
        },
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#20cc9400' },
              { offset: 1, color: '#20cc94' }
            ]
          }
        }
      }
    ]
  }
  visitCountRef.value && visitCountRef.value.setOption(options)
}

async function getHotTags () {
  const colors = ['#ef275c', '#ef27da', '#b027efc', '#4327ef', '#2791ef', '#27e5ef', '#27efad', '#efb327']
  const data = await apiGetHotTags<{ tagName: string }[]>()
  const options = {
    series: [
      {
        type: 'wordCloud',
        shape: 'circle',
        width: '100%',
        height: '100%',
        right: 20,
        bottom: 20,
        sizeRange: [12, 30],
        rotationRange: [-90, 90],
        rotationStep: 45,
        gridSize: 6,
        textStyle: {
          fontFamily: 'sans-serif',
          fontWeight: 'bold',
          color: () => {
            const idx = Math.floor(Math.random() * colors.length)
            return colors[idx]
          }
        },
        emphasis: {
          focus: 'self',
          textStyle: {
            textShadowBlur: 10,
            textShadowColor: '#333'
          }
        },
        data: [...data, ...data].map((o, index) => {
          return {
            name: o.tagName.toUpperCase(),
            value: index
          }
        })
      }
    ]
  }
  hotTagRef.value && hotTagRef.value.setOption(options)
}

async function getHotArticles () {
  const data = await apiGetHotArticles<Article[]>()
  rankArticleList.value = data
}

async function getCityVisitCounts () {
  const data = await apiGeCityVisitCount<any[]>()
  cityVisitCounts.value = data
}

function chartEventResize () {
  const resizeOptions = {
    animation: {
      duration: 500
    }
  }
  publishTrendRef.value && publishTrendRef.value.resize(resizeOptions)
  visitCountRef.value && visitCountRef.value.resize(resizeOptions)
  hotTagRef.value && hotTagRef.value.resize(resizeOptions)
}

function navatatorLink (path: string) {
  router.push(path)
}

statisticCountall()
getPublicTrend()
getVisitCounts()
getHotTags()
getHotArticles()
getCityVisitCounts()
</script>

<style scoped lang="scss">
@font-face {
  font-family: FangXingYan;
  src: url('@/assets/font-family/FangXingYan.ttf');
}
.page-control-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  .top-gird {
    display: flex;
    align-items: center;
    height: 136px;
    .welcome {
      width: 380px;
      display: flex;
      background: #e1eaf9;
      margin-right: 0.5%;
      height: 100%;
      border-radius: 4px;
      padding: 12px;
      box-sizing: border-box;
      align-items: center;
      img {
        height: 100%;
        display: block;
      }
      .text {
        padding-left: 20px;
        p {
          font-size: 18px;
          color: #3f6ad8;
          line-height: 28px;
        }
      }
    }
    .panel-card {
      display: flex;
      justify-content: space-between;
      height: 100%;
      flex: 1;
      &-item {
        width: 24.5%;
        border-radius: 4px;
        background: #fff;
        padding: 12px;
        box-sizing: border-box;
        text-align: center;
        img {
          margin: 0 auto;
          display: block;
          position: relative;
          left: -2px;
        }
        span {
          font-size: 14px;
          display: inline-block;
          color: #999;
          display: block;
        }
        p {
          font-size: 28px;
          font-weight: 600;
          margin-top: 10px;
          color: #171616;
          font-family: FangXingYan;
          cursor: pointer;
        }
      }
    }
  }
  .bottom-gird {
    height: 0;
    flex: 1;
    display: flex;
    flex-direction: column;

    .modal {
      margin-top: 8px;
      flex: 1;
      height: 0;
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      grid-gap: 8px;
      &.col-2 {
        grid-template-columns: 1fr 1fr;
      }
      .block {
        background: #fff;
        border-radius: 2px;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        .title {
          line-height: 42px;
          padding: 0 12px;
          border-bottom: 1px solid #f1f1f1;
          display: flex;
          align-items: center;
          position: relative;
          p{
            color: #999;
          }
          i {
            font-size: 22px;
            margin-right: 6px;
          }
        }
        .c {
          height: 0;
          flex: 1;
        }
        #hotArticle {
          padding: 6px;
          box-sizing: border-box;
          :deep(.el-table) {
            .el-table__inner-wrapper {
              &::before {
                display: none;
              }
            }
            .el-table__header {
              tr {
                th {
                  padding: 8px 0;
                  font-weight: 600;
                  color: #999;
                  background-color: #fafafa;
                  border: none;
                  .cell {
                    font-size: 12px;
                    letter-spacing: 2px;
                  }
                }
              }
            }
            .el-table__body {
              tr {
                td {
                  padding: 8px 0;
                  color: #4c4c4c;
                  border: none;
                  .cell {
                    font-size: 12px;
                    .rank-span {
                      font-size: 12px;
                      background: #dfdfdf;
                      padding: 0 8px;
                      border-radius: 2px;
                      color: #fff;
                    }
                  }
                }
                &:first-child {
                  .rank-span {
                    background: #e31616 !important;
                  }
                }
                &:nth-child(2) {
                  .rank-span {
                    background: #41e3df !important;
                  }
                }
                &:nth-child(3) {
                  .rank-span {
                    background: #fca108 !important;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
